In [2]:
import tensorflow as tf
tf.__version__
Out[2]:
In [24]:
#load data
mnist = tf.keras.datasets.mnist #28*28 hand-written digits
(x_train, y_train), (x_test, y_test) = mnist.load_data()
x_train = tf.keras.utils.normalize(x_train, axis=1) #normalize
x_test = tf.keras.utils.normalize(x_test, axis=1) ##normalize
In [19]:
#show one image
import matplotlib.pyplot as plt
plt.imshow(x_train[0], cmap = plt.cm.binary) #cmap = calor map, show image as grayscale
plt.show()
In [20]:
#model define
model = tf.keras.models.Sequential()
model.add(tf.keras.layers.Flatten(input_shape=(28, 28))) #flat the input images to vectors
model.add(tf.keras.layers.Dense(128, activation = tf.nn.relu))
model.add(tf.keras.layers.Dense(128, activation = tf.nn.relu))
model.add(tf.keras.layers.Dense(10, activation = tf.nn.softmax)) #out
model.compile(optimizer='adam',
loss='sparse_categorical_crossentropy',
metrics=['accuracy']
)
model.fit(x_train, y_train, epochs=3)
Out[20]:
In [22]:
val_loss, val_acc = model.evaluate(x_test, y_test)
print(val_loss, val_acc)
In [25]:
model.save('epic_num_reader.model')
new_model = tf.keras.models.load_model('epic_num_reader.model')
predictions = new_model.predict([x_test])
print(predictions)
In [27]:
import numpy as np
print(np.argmax(predictions[0]))
In [28]:
plt.imshow(x_test[0])
plt.show()
In [ ]: